﻿using Paperless.Entities;
using Paperless.Models;
using Paperless.Repositories;
using System.Web.Http;
using System.Linq;
using AutoMapper;
using System.Collections.Generic;
using System.Threading.Tasks;
using System;
using Microsoft.AspNet.Identity;

namespace Paperless.Controllers
{
    [Route("api/transaction/{transactionId}/note/{id?}")]
    public class NoteController : ApiController
    {
        public IRepository<Note> Repository { get; private set; }

        public NoteController(IRepository<Note> repository)
        {
            Repository = repository;
        }

        public IHttpActionResult GetByTransactionId(long transactionId)
        {
            var entities = Repository.DbSet().Where(x => x.TransactionId == transactionId)
                .OrderBy(x => x.CreatedDate);

            var model = Mapper.Map<IEnumerable<NoteViewModel>>(entities);

            return Ok(model);
        }

        public async Task<IHttpActionResult> Post(NoteModel model, long transactionId)
        {
            model.CreatedBy = User.Identity.GetUserName();
            model.CreatedDate = DateTime.Now;
            model.TransactionId = transactionId;

            var entity = Mapper.Map<Note>(model);

            try
            {
                entity.Agents = model.AgentIds.Select(agentId => new Agent() { Id = agentId }).ToList();
                await Repository.Add(entity);
            }
            catch (Exception e)
            {
                return InternalServerError(e);
            }

            return Ok(entity.Id);
        }

        public async Task<IHttpActionResult> Delete(long id)
        {
            try
            {
                await Repository.Remove(id);
            }
            catch (Exception e)
            {
                return InternalServerError(e);
            }

            return Ok();
        }
    }
}